package com.lei.chinese_herbal_medicine.Interceptor;

import com.lei.chinese_herbal_medicine.Entity.Token;
import com.lei.chinese_herbal_medicine.Service.TokenService;
import com.lei.chinese_herbal_medicine.Util.DateUtil;
import com.lei.chinese_herbal_medicine.Util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private TokenService tokenService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            System.out.println("OPTIONS请求，放行");
            return true;
        }
        Token token=new Token();
        String tokenStr=request.getHeader("Authorization");
        if(tokenStr==null||"".equals(tokenStr.trim())){//未登录
            System.out.println("未登录");
            return false;
        }
        token.setId(tokenStr);
        token=tokenService.getToken(token);
        if(token==null){//该token不存在
            System.out.println("该token不存在");
            return false;
        }
        Token t=null;
        if(DateUtil.isExpired(token.getExpirationTime())){//token过期
            t=new Token();
            t.setId(token.getId());
            t.setLastUpdateTime(new Date());
            t.setStatus("expired");
            tokenService.updateToken(t);
            System.out.println("token过期");
            return false;
        }else{
            t=new Token();
            t.setId(token.getId());
            t.setLastUpdateTime(new Date());
            t.setExpirationTime(DateUtil.getLaterDate(60));
            tokenService.updateToken(t);
            System.out.println("访问成功");
            return true;
        }
    }
}
